use crate::{config::DB_PATH, error::AppErr};
use sqlx::SqlitePool;
use std::mem::MaybeUninit;

pub mod device;
pub mod firm;
pub mod user;
pub mod product;
pub mod cargo_config;
pub mod cargo_state;
pub mod replenish;
pub mod order;
pub mod product2;

static mut POOL: MaybeUninit<SqlitePool> = MaybeUninit::uninit();

pub async fn init() -> Result<(), AppErr> {
    let url = format!("sqlite://{}?mode=rwc", DB_PATH);
    let pool = SqlitePool::connect(&url).await?;
    unsafe {
        POOL.write(pool);
    }

    device::init().await?;
    firm::init().await?;
    user::init().await?;
    product::init().await?;
    order::init().await?;
    replenish::init().await?;
    cargo_config::init().await?;
    cargo_state::init().await?;
    product2::init().await?;

    Ok(())
}

pub fn get_pool() -> &'static SqlitePool {
    unsafe { POOL.assume_init_ref() }
}
